<template>
	<view class="container">
		<view class="page-title">我的名片</view>
		
		<!-- 用户信息卡片 -->
		<view class="user-card">
			<view class="avatar-section">
				<image class="avatar" 
					   :src="userInfo.avatar || '/static/default-avatar.png'" 
					   mode="aspectFill"></image>
				<button class="avatar-btn" @click="chooseAvatar">更换头像</button>
			</view>
			
			<view class="info-section">
				<!-- 基本信息 -->
				<view class="input-group">
					<view class="input-label">姓名</view>
					<input class="form-input" 
						   v-model="userInfo.name" 
						   placeholder="请输入姓名" />
				</view>
				
				<view class="input-group">
					<view class="input-label">性别</view>
					<radio-group @change="handleGenderChange">
						<view class="radio-row">
							<label class="radio-item">
								<radio value="male" :checked="userInfo.gender === 'male'" />
								<text>男</text>
							</label>
							<label class="radio-item">
								<radio value="female" :checked="userInfo.gender === 'female'" />
								<text>女</text>
							</label>
						</view>
					</radio-group>
				</view>
				
				<view class="input-group">
					<view class="input-label">邮箱</view>
					<input class="form-input" 
						   v-model="userInfo.email" 
						   placeholder="请输入邮箱地址" />
				</view>
				
				<view class="input-group">
					<view class="input-label">部门</view>
					<input class="form-input" 
						   v-model="userInfo.department" 
						   placeholder="请输入所在部门" />
				</view>
				
				<view class="input-group">
					<view class="input-label">职位</view>
					<input class="form-input" 
						   v-model="userInfo.position" 
						   placeholder="请输入职位" />
				</view>
				
				<view class="input-group">
					<view class="input-label">地址</view>
					<textarea class="form-textarea" 
							  v-model="userInfo.address" 
							  placeholder="请输入地址"></textarea>
				</view>
				
				<view class="input-group">
					<view class="input-label">扩展信息</view>
					<textarea class="form-textarea" 
							  v-model="userInfo.extattr" 
							  placeholder="其他信息、备注等"></textarea>
				</view>
			</view>
		</view>
		
		<!-- 功能菜单 -->
		<view class="menu-section">
			<view class="menu-item" @click="goToMyDemands">
				<text class="menu-title">我的需求</text>
				<text class="menu-arrow">></text>
			</view>
			<view class="menu-item" @click="goToMatchCenter">
				<text class="menu-title">撮合中心</text>
				<text class="menu-arrow">></text>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-section">
			<button class="btn-primary save-btn" @click="saveUserInfo" :disabled="saving">
				{{ saving ? '保存中...' : '保存信息' }}
			</button>
			
			<button v-if="isLoggedIn" class="btn-danger logout-btn" @click="logout">
				退出登录
			</button>
			<button v-else class="btn-primary login-btn" @click="login">
				微信登录
			</button>
		</view>
		
		<!-- 登录状态显示 -->
		<view class="status-section">
			<text class="status-text">
				登录状态：{{ isLoggedIn ? '已登录' : '未登录' }}
			</text>
			<text v-if="isLoggedIn && userInfo.id" class="user-id">
				用户ID：{{ userInfo.id }}
			</text>
		</view>
	</view>
</template>

<script>
import { api } from '../../utils/request.js';
import authStore from '../../store/auth.js';

export default {
	data() {
		return {
			// 用户信息
			userInfo: {
				id: '',
				name: '',
				avatar: '',
				gender: '',
				email: '',
				department: '',
				position: '',
				address: '',
				extattr: ''
			},
			
			// 状态
			saving: false,
			loading: false
		}
	},
	
	computed: {
		// 是否已登录
		isLoggedIn() {
			return authStore.isLoggedIn();
		}
	},
	
	onLoad() {
		// 个人中心页面：显示用户信息，支持编辑和退出登录
		// 接口：GET /api/auth/user-info 和 PUT /api/auth/user-info
		if (this.isLoggedIn) {
			this.loadUserInfo();
		}
	},
	
	onShow() {
		// 每次显示页面时检查登录状态
		if (this.isLoggedIn) {
			this.loadUserInfo();
		} else {
			this.resetUserInfo();
		}
	},
	
	methods: {
		// 加载用户信息
		async loadUserInfo() {
			this.loading = true;
			
			try {
				const userInfo = await authStore.getUserInfo();
				this.userInfo = {
					id: userInfo.id || '',
					name: userInfo.name || '',
					avatar: userInfo.avatar || '',
					gender: userInfo.gender || '',
					email: userInfo.email || '',
					department: userInfo.department || '',
					position: userInfo.position || '',
					address: userInfo.address || '',
					extattr: userInfo.extattr || ''
				};
				
			} catch (error) {
				console.error('加载用户信息失败:', error);
				// 如果获取用户信息失败，可能token已过期，清除登录状态
				if (error.message && error.message.includes('401')) {
					authStore.logout();
					this.resetUserInfo();
				}
			} finally {
				this.loading = false;
			}
		},
		
		// 重置用户信息
		resetUserInfo() {
			this.userInfo = {
				id: '',
				name: '',
				avatar: '',
				gender: '',
				email: '',
				department: '',
				position: '',
				address: '',
				extattr: ''
			};
		},
		
		// 处理性别变化
		handleGenderChange(e) {
			this.userInfo.gender = e.detail.value;
		},

		// 选择头像
		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					// 这里简单设置本地路径，实际应用中需要上传到服务器
					this.userInfo.avatar = res.tempFilePaths[0];
				},
				fail: (error) => {
					console.error('选择头像失败:', error);
					uni.showToast({
						title: '选择头像失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 保存用户信息
		async saveUserInfo() {
			if (!this.isLoggedIn) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}
			
			if (this.saving) return;
			
			this.saving = true;
			
			try {
				// 构建更新数据，只发送有值的字段
				const updateData = {};
				
				if (this.userInfo.name.trim()) {
					updateData.name = this.userInfo.name.trim();
				}
				if (this.userInfo.avatar) {
					updateData.avatar = this.userInfo.avatar;
				}
				if (this.userInfo.gender) {
					updateData.gender = this.userInfo.gender;
				}
				if (this.userInfo.email.trim()) {
					updateData.email = this.userInfo.email.trim();
				}
				if (this.userInfo.department.trim()) {
					updateData.department = this.userInfo.department.trim();
				}
				if (this.userInfo.position.trim()) {
					updateData.position = this.userInfo.position.trim();
				}
				if (this.userInfo.address.trim()) {
					updateData.address = this.userInfo.address.trim();
				}
				if (this.userInfo.extattr.trim()) {
					updateData.extattr = this.userInfo.extattr.trim();
				}
				
				await authStore.updateUserInfo(updateData);
				
				// 更新成功后重新加载用户信息
				this.loadUserInfo();
				
			} catch (error) {
				console.error('保存用户信息失败:', error);
			} finally {
				this.saving = false;
			}
		},
		
		// 微信登录
		async login() {
			try {
				await authStore.loginWithWeixin();
				this.loadUserInfo();
			} catch (error) {
				console.error('登录失败:', error);
			}
		},
		
		// 退出登录
		logout() {
			uni.showModal({
				title: '确认退出',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						authStore.logout();
						this.resetUserInfo();
					}
				}
			});
		},
		
		// 跳转到我的需求页面
		goToMyDemands() {
			uni.navigateTo({ url: '/pages/demand/mine' });
		},
		
		// 跳转到撮合中心
		goToMatchCenter() {
			uni.switchTab({ url: '/pages/match/index' });
		}
	}
}
</script>

<style scoped>
.user-card {
	background: white;
	margin-bottom: 30rpx;
	padding: 40rpx;
	border-radius: 12rpx;
}

.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 40rpx;
}

.avatar {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	border: 4rpx solid #e1e1e1;
	margin-bottom: 20rpx;
}

.avatar-btn {
	background-color: #f0f0f0;
	color: #666;
	border: none;
	border-radius: 6rpx;
	padding: 15rpx 30rpx;
	font-size: 26rpx;
}

.info-section {
	margin-top: 30rpx;
}

.form-textarea {
	border: 2rpx solid #e1e1e1;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	width: 100%;
	box-sizing: border-box;
	min-height: 100rpx;
	resize: none;
}

.radio-row {
	display: flex;
	gap: 40rpx;
}

.radio-item {
	display: flex;
	align-items: center;
	gap: 10rpx;
	font-size: 28rpx;
}

.menu-section {
	background: white;
	margin-bottom: 30rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.menu-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 40rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-title {
	font-size: 30rpx;
	color: #333;
}

.menu-arrow {
	font-size: 28rpx;
	color: #999;
}

.action-section {
	margin-bottom: 30rpx;
}

.save-btn {
	width: 100%;
	padding: 30rpx 0;
	font-size: 32rpx;
	margin-bottom: 30rpx;
}

.logout-btn {
	width: 100%;
	padding: 30rpx 0;
	font-size: 32rpx;
}

.login-btn {
	width: 100%;
	padding: 30rpx 0;
	font-size: 32rpx;
}

.status-section {
	background: #f8f8f8;
	padding: 30rpx;
	border-radius: 12rpx;
	text-align: center;
}

.status-text {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.user-id {
	font-size: 26rpx;
	color: #999;
}
</style>